package cn.jslancer.webx.router;

import cn.jslancer.webx.handler.Handler;
import io.netty.handler.codec.http.HttpMethod;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author jslancer
 * @date 2018/7/29 21:23
 */
public class RouteImpl implements Route, Comparable<RouteImpl> {

    private RouterImpl router;

    private int order;

    private Set<HttpMethod> methods = new HashSet<>();

    private String path;

    private List<Handler<RoutingContext>> contextHandlers;

    public RouteImpl(RouterImpl router, int order) {
        this.router = router;
        this.order = order;

        this.contextHandlers = new ArrayList<>();
    }

    public RouteImpl(RouterImpl router, int order, HttpMethod method, String path) {
        this(router, order);
        this.methods.add(method);
        this.path = path;
    }

    public RouteImpl(RouterImpl router, int order, String path) {
        this(router, order);
        this.path = path;
    }

    @Override
    public synchronized Route method(HttpMethod method) {
        methods.add(method);
        return this;
    }

    @Override
    public synchronized Route path(String path) {
        this.path = path;
        return this;
    }

    @Override
    public synchronized Route handler(Handler<RoutingContext> handler) {
        this.contextHandlers.add(handler);
        // 延迟加载
        this.router.addRoute(this);

        this.router.addRoute(path, this);
        return this;
    }

    @Override
    public synchronized Route order(int order) {
        this.order = order;
        return this;
    }


    void handleContext(RoutingContext context) {
        this.contextHandlers.forEach(e -> {
            e.handle(context);
        });
    }

    @Override
    public int compareTo(RouteImpl o) {
        return order - o.order;
    }


//    @Override
//    public Router router() {
//        return router;
//    }
}
